import React, { useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import { useRequest } from 'ahooks';
import { Button, List, Popconfirm, message } from 'antd';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons';
import nl2sqlService from '@/api/services/nl2sqlService';
import { ConnectionInfo } from '@/types/nl2sql/type';
import { Empty, Search } from '@/components/eai-design';
import { useParams } from '@/router/hooks';
import DatabaseAccessModal from './database-access-modal';

interface DatabaseListProps {
  onDeleteDatabase?: (connectionId: string) => void;
  onConnectionsUpdate?: (connections: ConnectionInfo[]) => void;
  onConnectionSelect?: (connection: ConnectionInfo | null) => void;
  selectedConnection?: ConnectionInfo | null;
}

export interface DatabaseListRef {
  refresh: () => void;
}

const DatabaseList = forwardRef<DatabaseListRef, DatabaseListProps>(({
  onDeleteDatabase,
  onConnectionsUpdate,
  onConnectionSelect,
  selectedConnection,
}, ref) => {
  const [searchValue, setSearchValue] = useState('');
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [modalVisible, setModalVisible] = useState(false);
  const [selectedConnectionForEdit, setSelectedConnectionForEdit] = useState<ConnectionInfo | null>(null);

  const {appId} = useParams() as {appId: string};
  
  // 获取数据库连接列表
  const { data: connections = {databaseInfos: [], total: 0}, loading, refresh } = useRequest(
    () => nl2sqlService.getConnections({
      app_id: appId,
      isPage: false,
      offset: -1,
      page: pagination.current,
      page_size: pagination.pageSize,
    }),
    {
      refreshDeps: [pagination.current, pagination.pageSize],
      onError: (error) => {
        message.error('获取数据库连接列表失败');
        console.error('获取数据库连接列表失败:', error);
      },
      onSuccess: (data) => {
        console.log('data', data);
        onConnectionsUpdate?.(data?.databaseInfos);
        
        // 检查返回的数据库列表长度是否大于当前长度
        const isLengthIncreased = data?.databaseInfos?.length > connections.databaseInfos.length;
        
        if (isLengthIncreased && data?.databaseInfos) {
          // 如果长度增加了，默认选中第一个有效的连接
          const validConnections = data.databaseInfos.filter(
            (conn: ConnectionInfo) => conn.table_simple_infos && conn.table_simple_infos.length > 0
          );
          if (validConnections.length > 0) {
            onConnectionSelect?.(validConnections[0]);
          }
        } else if (selectedConnection && data?.databaseInfos) {
          // 如果当前有选中的连接，检查它是否仍然存在并更新
          const updatedConnection = data.databaseInfos.find(
            conn => conn.database_id === selectedConnection.database_id
          );
          if (updatedConnection) {
            // 如果连接仍然存在，更新选中的连接信息
            onConnectionSelect?.(updatedConnection);
          } else {
            // 如果连接不存在了，尝试选择第一个有效的连接
            const validConnections = data.databaseInfos.filter(
              (conn: ConnectionInfo) => conn.table_simple_infos && conn.table_simple_infos.length > 0
            );
            if (validConnections.length > 0) {
              onConnectionSelect?.(validConnections[0]);
            } else {
              onConnectionSelect?.(null as any);
            }
          }
        }
        
        // 如果接口返回了总数，更新分页信息
        if (data && typeof data === 'object' && 'total' in data) {
          setPagination(prev => ({
            ...prev,
            total: (data as any).total || 0,
          }));
        }
      },
    }
  );

  // 暴露refresh方法给父组件
  useImperativeHandle(ref, () => ({
    refresh,
  }), [refresh]);

  // 过滤数据：排除table_simple_infos为空列表的数据，并根据搜索值过滤
  const filteredConnections = connections.databaseInfos.filter((connection: ConnectionInfo) => {
    const hasTables = connection.table_simple_infos && connection.table_simple_infos.length > 0;
    const matchesSearch = searchValue 
      ? connection.display_name.toLowerCase().includes(searchValue.toLowerCase())
      : true;
    return hasTables && matchesSearch;
  });

  // 处理删除数据库连接
  const handleDelete = async (connectionId: string) => {
    try {
      await nl2sqlService.deleteConnection(connectionId);
      message.success('删除成功');
      
      // 删除成功后，如果删除的是当前选中的连接，需要重新选择
      if (selectedConnection?.database_id === connectionId) {
        // 获取删除后的连接列表
        const updatedConnections = connections.databaseInfos.filter(
          (conn: ConnectionInfo) => conn.database_id !== connectionId
        );
        
        // 过滤掉没有表格的连接
        const validConnections = updatedConnections.filter(
          (conn: ConnectionInfo) => conn.table_simple_infos && conn.table_simple_infos.length > 0
        );
        
        // 如果有有效的连接，选中第一个；否则设置为null
        if (validConnections.length > 0) {
          onConnectionSelect?.(validConnections[0]);
        } else {
          onConnectionSelect?.(null as any);
        }
      }
      
      refresh(); // 刷新列表
      onDeleteDatabase?.(connectionId);
    } catch (error) {
      message.error('删除失败');
      console.error('删除数据库连接失败:', error);
    }
  };

  // 处理编辑数据库连接
  const handleEdit = (connection: ConnectionInfo) => {
    setSelectedConnectionForEdit(connection);
    setModalVisible(true);
  };

  // 处理添加数据库连接
  const handleAddDatabase = () => {
    setSelectedConnectionForEdit(null);
    setModalVisible(true);
  };

  // 处理弹窗关闭
  const handleModalClose = () => {
    setModalVisible(false);
    setSelectedConnectionForEdit(null);
  };

  // 处理弹窗成功
  const handleModalSuccess = () => {
    setModalVisible(false);
    setSelectedConnectionForEdit(null);
    refresh(); // 刷新列表
  };

  // 处理分页变化
  const handlePageChange = (page: number, pageSize: number) => {
    setPagination(prev => ({
      ...prev,
      current: page,
      pageSize: pageSize,
    }));
  };

  // 处理搜索
  const handleSearch = (value: string) => {
    setSearchValue(value);
    setPagination(prev => ({
      ...prev,
      current: 1, // 搜索时重置到第一页
    }));
  };

  return (
    <div className="flex h-full w-full flex-col">
      
      {/* 添加按钮区域 */}
      <div className="mb-4 flex justify-end items-center">
        <Search 
          placeholder="搜索" 
          className="w-full"
          allowClear
          value={searchValue}
          onChange={(e)=>{
            handleSearch(e.target.value);
          }}
        />
        <Button 
          onClick={handleAddDatabase}
          className="flex items-center justify-center mx-2"
          title="添加数据库"
        >
          <span className="text-lg">+</span>
        </Button>
      </div>

      {/* 数据库连接列表 */}
      {loading ? (
        <div className="flex-1 flex items-center justify-center">
          <div className="text-gray-500">加载中...</div>
        </div>
      ) : filteredConnections.length > 0 ? (
        <div className="nl2sql-database-list flex-1 overflow-y-auto [-ms-overflow-style:none] [scrollbar-width:none]">
          <List
            dataSource={filteredConnections}
            renderItem={(connection: ConnectionInfo) => {
              const isSelected = selectedConnection?.database_id === connection.database_id;
              return (
                <List.Item
                  className={`mb-2 cursor-pointer rounded-lg transition-colors ${
                    isSelected
                      ? 'border-blue-500 bg-bg-4 hover:bg-blue-100 !text-@brand-color'
                      : 'border-gray-200 bg-gray-50 hover:bg-gray-100'
                  } !px-3 py-2`}
                  onClick={() => {
                    onConnectionSelect?.(connection);
                  }}
                  key={connection.database_id}
                  actions={[
                    <Button
                      key="edit"
                      type="text"
                      size="small"
                      icon={<EditOutlined />}
                      onClick={(e) => {
                        e.stopPropagation();
                        handleEdit(connection);
                      }}
                      className={`${
                        isSelected ? 'text-blue-600 hover:text-blue-700' : 'text-gray-600 hover:text-blue-600'
                      }`}
                      title="编辑"
                    />,
                    <Popconfirm
                      key="delete"
                      title="确定要删除这个数据库连接吗？"
                      onConfirm={(e) => {
                        e?.stopPropagation();
                        handleDelete(connection.database_id);
                      }}
                      okText="确定"
                      cancelText="取消"
                    >
                      <Button
                        type="text"
                        size="small"
                        icon={<DeleteOutlined />}
                        onClick={(e) => e.stopPropagation()}
                        className={`${
                          isSelected ? 'text-blue-600 hover:text-red-600' : 'text-gray-600 hover:text-red-600'
                        }`}
                        title="删除"
                      />
                    </Popconfirm>
                  ]}
                >
                  <div className="flex-1 min-w-0 mr-2">
                    <div
                      className={`text-sm font-medium flex items-center h-[24px] ${
                        isSelected ? 'text-blue-700' : 'text-blue-600'
                      } overflow-hidden whitespace-nowrap text-ellipsis`}
                      title={connection.display_name}
                    >
                      {connection.display_name}
                    </div>
                  </div>
                </List.Item>
              );
            }}
          />
        </div>
      ) : (
        <div className="flex-1 flex items-center justify-center">
          <div className="text-center">
            <Empty fontText="暂无数据库" />
            {connections.databaseInfos.length === 0 && <Button type="default" className="w-full mt-4" onClick={handleAddDatabase}>
              立即添加
            </Button>}
          </div>
        </div>
      )}

      {/* 接入数据库弹窗 */}
      <DatabaseAccessModal
        open={modalVisible}
        onClose={handleModalClose}
        onSuccess={handleModalSuccess}
        connection={selectedConnectionForEdit}
        connections={connections.databaseInfos}
        handleConnectionSelect={onConnectionSelect}
      />
    </div>
  );
});

export default DatabaseList; 